package com.travel.modules.sys.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import com.travel.config.AliOSSConfig;
import com.travel.modules.sys.service.AliOSSService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.Date;

@Slf4j
@Service("aliOSSService")
public class AliOSSServiceImpl implements AliOSSService {
    @Resource
    private AliOSSConfig aliOSSConfig;

    @Override
    public String root(String fileName, InputStream is) {
        return upload(fileName, "", is);
    }

    @Override
    public String scenic(String fileName, InputStream is) {
        return upload(fileName, aliOSSConfig.getScenic(), is);
    }

    @Override
    public String hotel(String fileName, InputStream is) {
        return upload(fileName, aliOSSConfig.getHotel(), is);
    }

    @Override
    public String route(String fileName, InputStream is) {
        return upload(fileName, aliOSSConfig.getRoute(), is);
    }

    @Override
    public String advertise(String fileName, InputStream is) {
        return upload(fileName, aliOSSConfig.getAdvertise(), is);
    }

    @Override
    public String avatar(String fileName, InputStream is) {
        return upload(fileName, aliOSSConfig.getAvatar(), is);
    }

    @Override
    public String strategy(String fileName, InputStream is) {
        return upload(fileName, aliOSSConfig.getStrategy(), is);
    }

    /**
     * 上传
     * @param fileName 文件名
     * @param folder 文件夹路径
     * @param is 文件IO流
     * @return url
     */
    public String upload(String fileName, String folder, InputStream is) {
        String key = folder + fileName;
        OSS ossClient = new OSSClient(aliOSSConfig.getEndPoint(),aliOSSConfig.getAccessKeyId(), aliOSSConfig.getAccessKeySecret());
        ObjectMetadata meta = new ObjectMetadata();
        try {
            meta.setContentLength(is.available());
        } catch (IOException e) {
            e.printStackTrace();
        }
        meta.setCacheControl("no-cache");
        meta.setHeader("Pragma", "no-cache");
        meta.setContentType("image/jpeg");
        meta.setContentDisposition("filename=" + fileName);
        meta.setObjectAcl(CannedAccessControlList.PublicReadWrite);
        ossClient.putObject(aliOSSConfig.getBucketName(), key, is, meta);
        String url = ossClient.generatePresignedUrl(aliOSSConfig.getBucketName(), key, new Date(new Date().getTime() + (1000L * 60 * 60 * 24 * 365 * 100))).toString();
        ossClient.shutdown();
        return url;
    }
}
